package com.googlecode.gamedroid.event.source;

import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/*
 * create a button dispatcher, put it in the background and make it fill the whole window. add GameButtons to the
 * dispatcher, it will handle all unconsumed MotionEvents and pass it to the right buttons. Don't use this view as the
 * root view, it has to be next to the rest of the view hierarchy!
 */
public class ButtonDispatcher extends View
{
	private static final float SIZE_ADJUST = (float) 0.75; // TODO add preference
	List<GameButton> mButtons = new LinkedList<GameButton>();
	
	public ButtonDispatcher(Context context)
	{
		super(context);
	}
	
	public ButtonDispatcher(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}
	
	public ButtonDispatcher(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
	}
	
	private double getDistance(int[] size, float x, float y)
	{
		float dx, dy;
		
		if(x < size[0])
			dx = size[0] - x;
		else if(x > size[2])
			dx = x - size[2];
		else
			dx = 0;
		
		if(y < size[1])
			dy = size[1] - y;
		else if(y > size[3])
			dy = y - size[3];
		else
			dy = 0;
		
		return Math.sqrt(dx * dx + dy * dy);
	}
	
	public void add(GameButton button)
	{
		mButtons.add(button);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		int ignored_pointer = -1;
		if(event.getActionMasked() == MotionEvent.ACTION_UP || event.getActionMasked() == MotionEvent.ACTION_POINTER_UP)
			ignored_pointer = event.getActionIndex();
		
		MotionEvent.PointerCoords coords = new MotionEvent.PointerCoords();
		double distance;
		boolean pressed;
		
		for(GameButton button : mButtons)
		{
			pressed = false;
			
			for(int i = 0; i < event.getPointerCount(); i++)
			{
				if(ignored_pointer != -1 && ignored_pointer == i)
					continue;
				
				event.getPointerCoords(i, coords);
				
				distance = getDistance(button.getSize(), coords.x, coords.y);
				if(distance < coords.touchMajor / 2 * SIZE_ADJUST)
				{
					pressed = true;
					break;
				}
			}
			
			button.setPressed(pressed);
		}
		return true;
	}
}
